package com.jy.adscm.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.bean.system.JyDept;
import com.jy.adscm.bean.system.JyMenu;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.system.mapper.mysql.JyDeptMapper;
import com.jy.adscm.system.service.JyDeptService;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 机构信息 服务实现类
 * </p>
 *
 * @author yyy
 * @since 2018-08-01
 */
@Service
public class JyDeptServiceImpl extends ServiceImpl<JyDeptMapper, JyDept> implements JyDeptService {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    JyDeptMapper jyDeptMapper;

    @Override
    public void delDept(int deptId) throws AdscmSystemException {
        logger.info("删除部门【"+deptId+"】");
        try{
            JyDept dept = jyDeptMapper.selectById(deptId);
            if (AdscmBaseUtils.getInstance().isNotEmpty(dept,"id")){
                //如果部门下面有人的话，不能删除
                //先直接删除
                jyDeptMapper.deleteById(deptId);
            }else {
                throw new AdscmSystemException("删除部门失败，没有找到id为【"+deptId+"】的部门信息");
            }


        }catch (Exception e){
            throw new AdscmSystemException("删除部门失败："+e.getMessage());
        }
    }

    @Override
    public List<JyDept> getAllDept() throws AdscmSystemException {
        logger.info("查询所有部门信息");

        JyDept rootDept = jyDeptMapper.selectById(1);//顶级机构

        EntityWrapper<JyDept> wapper = new EntityWrapper();
        wapper.where("parent_dept is not null ");
        if (AdscmBaseUtils.getInstance().isNotEmpty(rootDept,"id")){
            List<JyDept> depts = jyDeptMapper.selectList(wapper);

            if (depts != null && depts.size()>0){
                recursionJyDept(rootDept,depts);
            }
            return rootDept.getChildren();
        }else {
            throw new AdscmSystemException("没有查询到顶级部门...");
        }


    }

    /**
     * 递归获取所有子机构进行构造
     * @param topLevelDept ：顶级机构
     * @param depts：所有机构
     * @return
     */
    private void recursionJyDept(JyDept topLevelDept,List<JyDept> depts){
        List<JyDept> childrenDepts = new ArrayList<>();
        for (JyDept dept : depts) {
            if (dept.getParentDept() != null && dept.getParentDept().intValue() == topLevelDept.getId().intValue()){
                childrenDepts.add(dept);
            }
        }

        if (childrenDepts.size()>0){
            for (JyDept dept:
                    childrenDepts) {
                recursionJyDept(dept,depts);
            }
        }
        topLevelDept.setChildren(childrenDepts);
    }
}
